﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CalculatorArithmetic
{
    class CalculateExp
    {
        Stack<Double> operandStack = new Stack<Double>();//建立栈来保存操作数和暂时计算结果
        double operand1, operand2;//两个操作数
        public void GetTwoOperands()//从栈中弹出两个操作数
        {
            operand1 = operandStack.Pop();
            operand2 = operandStack.Pop();
        }
        public string GetCalculateExp(string exp)
        {
            string[] postfixExp = exp.Split(',');//将后缀表达式转换成数组形式
            for (int i = 0; i < postfixExp.Length; i++)//遍历每个数组元素
            {
                switch (postfixExp[i])//当元素为符号时，从栈中弹出两个操作数进行相应的操作，是数字则压栈
                {
                    case "+":
                        GetTwoOperands();
                        operandStack.Push(operand2 + operand1);
                        break;
                    case "-":
                        GetTwoOperands();
                        operandStack.Push(operand2 - operand1);
                        break;
                    case "*":
                        GetTwoOperands();
                        operandStack.Push(operand2 * operand1);
                        break;
                    case "/":
                        GetTwoOperands();
                        if (operand1 == 0.0)
                        {
                            return "除数不能为0！";
                        }
                        else
                            operandStack.Push(operand2 / operand1);
                        break;
                    default://后缀表达式除了符号就是数字，所以default执行压栈
                        operandStack.Push(Convert.ToDouble(postfixExp[i]));
                        break;
                }
            }
            return Convert.ToString(operandStack.Pop());//返回栈里最后一个元素，既所求计算结果
        }
    }
}
